<?php

namespace Beerus\Modules\Brand\Controllers;

use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Biz\model\brand\Brand as mBrand;
use Biz\model\brand\BrandPackage;
use Biz\service\brand\Brand as sBrand;
use Doraemon\model\Category as mCategory;
use Doraemon\service\Category as sCategory;
use Doraemon\service\Tag as sTag;
use Doraemon\tools\Hhzurl;
use Doraemon\tools\ImgUrl;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Form;
use Hhz\AdministrativeRegion\Region;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;


const PAGE_SIZE = 20;
/**
 * 内部品牌清单
 *
 * @category   Module name
 * @package    PSR
 * @subpackage Documentation\API
 * @author     zhouyang  <zhouyang@haohaozhu.com>
 * @license    GPL http://www.haohaozhu.com
 * @link       http://www.haohaozhu.com
 */
class BrandController extends Controller
{
    public function index(Request $request, Content $content)
    {
        $data = [];
        $data['brandName'] = $request->input("brand_name");
        $data['id'] = $request->input("id");
        $data['uid'] = $request->input("uid");
        $data['brand_type'] = $request->input('brand_type');//品牌身份
        $data['pack_type'] = $request->input("pack_type"); //套餐类型
        $data['is_test'] = $request->input("is_test"); //是否测试号
        $status = $request->input('status', null);
        if (!is_null($status) && strlen($status) > 0) {
            $data['status'] = $status;
        } else {
            $data['status'] = [mBrand::STATUS_DELETE, mBrand::STATUS_USING];
        }
        $page = $request->input("page") ?: 1;
        $pageSize = $request->input("per_page", PAGE_SIZE);
        $limit = [
            ($page - 1) * $pageSize,
            $pageSize
        ];
        //获取品牌数据
        $brands = sBrand::getAdBrand($data, [], $limit);
        $gridModel = new pGridDataModel($brands['list'], $brands['count'], [
            'perPage' => $pageSize
        ]);
        $categories = sCategory::getFatherCategorys();
        return $content
            ->header('内部品牌清单')
            ->description(' ')
            ->row(
                Admin::grid($gridModel,
                    function (Grid $grid) use ($gridModel, $categories) {
                        $grid->paginate($gridModel->getPerPage());
                        $grid->filter(function ($filter) use ($categories) {

                            // 去掉默认的id过滤器
                            $filter->disableIdFilter();
                            // 在这里添加字段过滤器
                            $filter->column(1 / 2, function ($filter) use ($categories) {
                                $filter->equal('brand_name', '品牌名称')->placeholder('请输入品牌名称');
                                $filter->equal('id', '品牌ID')->placeholder('品牌ID');
                                $filter->equal('uid', 'UID')->placeholder('UID');
                            });
                            $filter->column(1 / 2, function ($filter) use ($categories) {
                                $filter->equal('brand_type', '品牌身份')->select([
                                    1 => '到期品牌',
                                    2 => '认证品牌',
                                    3 => '精选品牌',
                                    4 => '超级品牌'
                                ]);
                                $filter->equal('pack_type', '品牌套餐')->select([
                                    1 => '基础版',
                                    2 => '高级版',
                                    3 => '高级pro版'
                                ]);
                                $filter->equal('is_test', '是否测试号')->select([
                                    0 => '否',
                                    1 => '是',
                                ]);
                                $filter->equal('status', '状态')->select([
                                    0 => '已删除',
                                    1 => '正常',
                                ]);
                            });

                            $filter->expand();//默认展开
                        });
                        $grid->disableExport();
                        $grid->disableRowSelector();
                        $grid->column('id', '品牌ID');
                        $grid->column('uid', 'UID');
                        $grid->column('nick_name', '用户昵称');
                        $grid->column('avatar', '用户图像')->display(function () {
                            $imgPath = $this->avatar;
                            $image = strlen($imgPath) ? "<img src='" . $imgPath . "' style='max-height:100px;max-width:100px;' class='img img-thumbnail' />" : "";
                            return $image;
                        });
                        $grid->column('logo', 'logo')->display(function () {
                            $imgPath = $this->logo;
                            $image = strlen($imgPath) ? "<img src='" . $imgPath . "' style='max-height:100px;max-width:100px;' class='img img-thumbnail' />" : "";
                            return $image;
                        });
                        $grid->column('brand_name', '品牌名称')->display(function () {
                            $html = '<ul class="list-unstyled">';
                            $html .= '<li>' . $this->brand_name . '</li>';
                            if ($this->status == mBrand::STATUS_DELETE) {
                                $html .= '<li><span style="color: red">【已删除】</span></li>';
                            }
                            $html .= '</ul>';
                            return $html;
                        });
                        $grid->column('type', '类型')->display(function () {
                            if ($this->type == 1) {
                                $type = "品牌";
                            } else {
                                $type = "店铺";
                            }
                            return '<div class="span-label"><span class="label label-success">' . $type . '</span></div>';
                        });
                        $grid->column('brand_type', '品牌身份')->display(function () {
                            return mBrand::BRAND_TYPE[$this->brand_type];
                        });
                        $grid->column('pack_type', '品牌套餐')->display(function () {
                            return BrandPackage::$packTypeDesc[$this->pack_type];
                        });
                        $grid->column('area_name', '所属地');
                        $grid->column('spu_num', '商品数');
                        $grid->column('wiki_num', 'Wiki数');
                        $grid->column('relate_num', '关联内容数');
                        $grid->column('click_buy_num', '	商品买过数');
                        $grid->column('is_test', '测试号')->switch([
                                'on' => [
                                    'value' => 1,
                                    'text' => '是'
                                ],
                                'off' => [
                                    'value' => 0,
                                    'text' => '否'
                                ],
                            ]
                        );
                        $grid->actions(function (Grid\Displayers\Actions $actions) {
                            $actions->disableEdit();
                            if ($actions->row->status == mBrand::STATUS_DELETE) {
                                $actions->disableDelete();
                            }
                            $actions->prepend('&nbsp;<a class="fa fa-edit" target="" href="' . url('/admin/brand/edit/' . $actions->row->id) . '">编辑</a>');
                            $actions->prepend('<a class="fa fa-chain" target ="_blank" href="' . '/admin/brand/brandArea/' . $actions->row->id . '">编辑品牌专区</a>');
                            $weeklyUrl = Hhzurl::getDomain() . '/brand/weekly?brand_id=' . $actions->row->id;
                            $actions->prepend('<a class="fa fa-envelope" href="javascript:layer.open({
                                type: 2,
                                title: \'品牌周报\',
                                maxmin: true,
                                area: [\'500px\', \'800px\'],
                                content: \'' . $weeklyUrl . '\'
                            });">品牌周报</a>');
                        });
                    }
                )
            );
    }

    public function edit(Content $content, $id = 0)
    {
        $info = $id ? sBrand::getBrandInfoById($id) : [];
        $province = '';
        $city = '';
        if ($info) {
            $province = $info['area_code'] ? Region::getFirstCode($info['area_code']) : '';
            $city = $info['area_code'] ? Region::getSunCode($info['area_code']) : '';
            $info['brand_logo'] = $info['logo'];
        }
        $info = $this->getAllCategoryOption($info);
        $form = new Form($info);
        $form->imgUpload('brand_logo', 'logo', false, [
            'isUpload' => true,
            'isGetUrl' => true,
            'imgType' => ImgUrl::APPTYPE_BIZ,
            'imgSize' => ImgUrl::IMAGE_SIZE_ORI_NPHONE
        ]);
        $form->radio('type', '类型')->options([1 => '品牌', 2 => '店铺'])->default(1);
        $form->text('id', '品牌id')->readonly();
        $form->text('brand_name', '品牌名称')->setWidth(4, 2)->required();
        $form->text('en_brand_name', '英文名')->setWidth(4, 2);
        $cityOption = Region::getCityListByProvinceCode((string)$province);
        $form->select('province', '省')->options(Region::getProvincesList())->default($province)->load('city',
            '/admin/extend/area/get');
        $form->select('city', '市')->options($cityOption)->default($city);
        $form->select('tag_id', '关联标签')->options($this->getAllTagOption())->default(0);
        $form->radio('wiki_status', '商品是否可见')->options([0 => '不可见', 1 => '可见'])->default(1);
        $form->radio('suggest_status', '是否推荐')->options([0 => '不推荐', 1 => '推荐', 3 => '优先推荐', 4 => '降级推荐'])->default(0);
        $form->radio('store_status', '商城状态')->options([1 => '未确认', 2 => '计划售卖', 3 => '售卖中', 0 => '不售卖'])->default(0);
        $form->textarea('discription', '简介');
        $form->textarea('detail', '介绍');
        foreach ($info['all_first_category'] as $k => $row) {
            $name = 'cate_first_' . $k;
            $label = $row['cate_name'];
            $option = $info['cate_first_' . $k . '_option'];
            $form->checkbox($name, $label)->options($option)->canCheckAll();
        }
        $obOption = $this->getObTagsOption();
        $form->checkbox('ob_tag', '关联ob标签')->options($obOption)->canCheckAll();

        $form->action('/admin/brand/save');
        $content->row($form);
        return $content
            ->header('品牌内部清单')
            ->description(' ')
            ->breadcrumb(['text' => '品牌内部清单']);
    }

    public function isTest(Request $request, $id)
    {
        $isTest = $request->post('is_test', null);
        try {
            if ($id && !is_null($isTest)) {
                mBrand::update(['is_test' => $isTest], ['id' => $id]);
                $success = [
                    'message' => '操作成功',
                    'status' => true
                ];
            } else {
                throw new \Exception('参数错误');
            }
        } catch (\Exception $e) {
            $success = [
                'message' => '操作失败,' . $e->getMessage(),
                'status' => false,
            ];
        }
        return response()->json($success);
    }

    public function del($id)
    {
        try {
            if ($id) {
                sBrand::deleBrandInfoById($id);
                $success = [
                    'message' => '操作成功',
                    'status' => true
                ];
            }
        } catch (\Exception $e) {
            $success = [
                'message' => '操作失败,' . $e->getMessage(),
                'status' => false,
            ];
        }
        return response()->json($success);
    }

    public function save(Request $request)
    {
        try {
            $params = $request->all();
            $categoryData = [];
            foreach ($params as $key => $value) {
                if (strpos($key, 'cate_first_') !== false) {
                    $value = array_filter($value);
                    if ($value) {
                        $firstId = substr($key, strlen('cate_first_'));
                        $categoryData[$firstId] = $value;
                    }
                }
            }
            $brandId = $params['id'] ?? 0;
            $areaCode = $params['city'] ?? '';
            $obTag = $params['ob_tag'] ? implode(',', $params['ob_tag']) : '';
            $postData = [
                'logo' => $params['brand_logo'],
                'type' => $params['type'],
                'brand_name' => $params['brand_name'],
                'en_brand_name' => $params['en_brand_name'],
                'tag_id' => $params['tag_id'],
                'wiki_status' => $params['wiki_status'],
                'suggest_status' => $params['suggest_status'],
                'store_status' => $params['store_status'],
                'discription' => $params['discription'],
                'detail' => $params['detail'],
                'location' => Region::getOldCodeByAreaCode($areaCode),
                'area_code' => $areaCode,
                'category_data' => $categoryData,
                'ob_tag' => $obTag,
            ];
            if ($brandId) {
                //编辑
                $brandId = sBrand::updateBrandInfoById($brandId, $postData);
            } else {
                //新建
                $brandId = sBrand::addBrand($postData);
            }
            $success = new MessageBag([
                'title' => '保存成功'
            ]);
            return redirect('/admin/brand/list?' . $request->getQueryString())->with(compact('success'));
        } catch (\Exception $e) {
            $error = new MessageBag([
                'title' => '保存失败,' . $e->getMessage()
            ]);
            return back()->with(compact('error'));
        }
    }

    public function getAllBrand()
    {
        $brands = sBrand::getAllBrand();
        $brands = array_map(function ($brand) {
            return [
                "id" => $brand["id"],
                "text" => $brand["brand_name"] . ($brand["en_brand_name"] ? " - " . $brand["en_brand_name"] : "")
            ];
        }, $brands);

        return response()->json([
            "code" => 0,
            "data" => $brands
        ]);
    }

    private function getAllTagOption()
    {
        $tags = sTag::getTagList();
        return array_column($tags, 'tag', 'id');
    }

    private function getAllCategoryOption($info)
    {
        $res = mCategory::selectByWhere([
            'status' => mCategory::STATUS_USING,
            'deep' => [1, 2]
        ], ['id', 'cate_name', 'deep', 'father_id']);
        $list = [];
        foreach ($res as $row) {
            $list[$row['deep']][$row['id']] = $row;
        }
        $firstList = $list[1];
        $secondList = $list[2];
        foreach ($secondList as $row) {
            $firstInfo = isset($firstList[$row['father_id']]) ? $firstList[$row['father_id']] : [];
            if ($firstInfo) {
                if (!isset($info['all_first_category'][$firstInfo['id']])) {
                    $info['all_first_category'][$firstInfo['id']] = [
                        'id' => $firstInfo['id'],
                        'cate_name' => $firstInfo['cate_name']
                    ];
                }
                if (!isset($info['cate_first_' . $firstInfo['id']])) {
                    $info['cate_first_' . $firstInfo['id']] = [];
                    $info['cate_first_' . $firstInfo['id'] . '_option'] = [];
                }
                $id = $row['id'];
                $cateName = str_replace('\t', '', $row['cate_name']);
                if ($info['category_ids'] && in_array($row['id'], $info['category_ids'])) {
                    $info['cate_first_' . $firstInfo['id']][] = $id;
                }
                $info['cate_first_' . $firstInfo['id'] . '_option'][$id] = $cateName;
            }
        }
        return $info;
    }

    private function getObTagsOption()
    {
        $tag = [
            "硬装",
            "风格灵感",
            "空间布局",
            "选建材",
            "装饰搭配",
            "选家电",
            "选家具",
            "日用好物",
            "收纳",
            "家务",
            "DIY",
            "租房改造",
            "植物",
            "美食",
            "探店旅行",
            "萌宠",
            "家有萌娃",
            "找设计师",
        ];
        return array_combine($tag, $tag);
    }
}
